<?php
/**
 * 消息模型
 * 作者: 王勇程 (laughskydragon@qq.com)
 */

namespace app\common\model;

use app\common\model\ModelBase;

class Message extends ModelBase
{
    // 表名

    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'user_id' => 'integer',
        'type' => 'integer',
        'level' => 'integer',
        'is_read' => 'integer',
        'read_time' => 'integer',
        'relation_id' => 'integer',
        'send_time' => 'integer',
        'expire_time' => 'integer',
        'status' => 'integer',
        'create_time' => 'integer',
        'update_time' => 'integer',
    ];
    
    // 消息类型常量
    const TYPE_SYSTEM = 1;      // 系统通知
    const TYPE_ORDER = 2;       // 订单消息
    const TYPE_VIP = 3;         // VIP消息
    const TYPE_WITHDRAW = 4;    // 提现消息
    const TYPE_ACTIVITY = 5;    // 活动消息
    
    // 消息级别常量
    const LEVEL_NORMAL = 1;     // 普通
    const LEVEL_IMPORTANT = 2;  // 重要
    const LEVEL_URGENT = 3;     // 紧急
    
    /**
     * 获取消息类型文本
     */
    public function getTypeTextAttr($value, $data)
    {
        $typeMap = [
            self::TYPE_SYSTEM => '系统通知',
            self::TYPE_ORDER => '订单消息',
            self::TYPE_VIP => 'VIP消息',
            self::TYPE_WITHDRAW => '提现消息',
            self::TYPE_ACTIVITY => '活动消息',
        ];
        
        return $typeMap[$data['type']] ?? '未知';
    }
    
    /**
     * 获取消息级别文本
     */
    public function getLevelTextAttr($value, $data)
    {
        $levelMap = [
            self::LEVEL_NORMAL => '普通',
            self::LEVEL_IMPORTANT => '重要',
            self::LEVEL_URGENT => '紧急',
        ];
        
        return $levelMap[$data['level']] ?? '普通';
    }
    
    /**
     * 获取发送时间格式化
     */
    public function getSendTimeTextAttr($value, $data)
    {
        return $data['send_time'] ? date('Y-m-d H:i:s', $data['send_time']) : '';
    }
    
    /**
     * 获取阅读时间格式化
     */
    public function getReadTimeTextAttr($value, $data)
    {
        return $data['read_time'] ? date('Y-m-d H:i:s', $data['read_time']) : '';
    }
    
    /**
     * 获取扩展数据解析
     */
    public function getExtraDataAttr($value)
    {
        return $value ? json_decode($value, true) : [];
    }
    
    /**
     * 设置扩展数据
     */
    public function setExtraDataAttr($value)
    {
        return is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
    }
    
    /**
     * 获取用户消息列表
     */
    public function getUserMessages($userId, $type = null, $isRead = null, $paginate = false)
    {
        $where = [
            'user_id' => $userId,
            'status' => 1
        ];
        
        // 过滤过期消息
        $currentTime = time();
        $where['expire_time'] = ['=', 0];
        $where['expire_time'] = ['>', $currentTime];
        
        if ($type !== null) {
            $where['type'] = $type;
        }
        
        if ($isRead !== null) {
            $where['is_read'] = $isRead;
        }
        
        return $this->getList($where, true, 'send_time desc', $paginate);
    }
    
    /**
     * 获取用户未读消息数量
     */
    public function getUserUnreadCount($userId, $type = null)
    {
        $where = [
            'user_id' => $userId,
            'is_read' => 0,
            'status' => 1
        ];
        
        // 过滤过期消息
        $currentTime = time();
        $where['expire_time'] = ['=', 0];
        $where['expire_time'] = ['>', $currentTime];
        
        if ($type !== null) {
            $where['type'] = $type;
        }
        
        return $this->stat($where, 'count');
    }
    
    /**
     * 标记消息为已读
     */
    public function markAsRead($messageId, $userId = null)
    {
        $where = ['id' => $messageId];
        
        if ($userId !== null) {
            $where['user_id'] = $userId;
        }
        
        $data = [
            'is_read' => 1,
            'read_time' => time(),
            'update_time' => time()
        ];
        
        return $this->updateInfo($where, $data);
    }
    
    /**
     * 批量标记消息为已读
     */
    public function markMultipleAsRead($messageIds, $userId = null)
    {
        $where = ['id' => ['in', $messageIds]];
        
        if ($userId !== null) {
            $where['user_id'] = $userId;
        }
        
        $data = [
            'is_read' => 1,
            'read_time' => time(),
            'update_time' => time()
        ];
        
        return $this->updateInfo($where, $data);
    }
    
    /**
     * 标记用户所有消息为已读
     */
    public function markAllAsRead($userId, $type = null)
    {
        $where = [
            'user_id' => $userId,
            'is_read' => 0,
            'status' => 1
        ];
        
        if ($type !== null) {
            $where['type'] = $type;
        }
        
        $data = [
            'is_read' => 1,
            'read_time' => time(),
            'update_time' => time()
        ];
        
        return $this->updateInfo($where, $data);
    }
    
    /**
     * 删除消息
     */
    public function deleteMessage($messageId, $userId = null)
    {
        $where = ['id' => $messageId];
        
        if ($userId !== null) {
            $where['user_id'] = $userId;
        }
        
        return $this->updateInfo($where, ['status' => 0, 'update_time' => time()]);
    }
    
    /**
     * 批量删除消息
     */
    public function deleteMultipleMessages($messageIds, $userId = null)
    {
        $where = ['id' => ['in', $messageIds]];
        
        if ($userId !== null) {
            $where['user_id'] = $userId;
        }
        
        return $this->updateInfo($where, ['status' => 0, 'update_time' => time()]);
    }
    
    /**
     * 清理过期消息
     */
    public function cleanExpiredMessages()
    {
        $currentTime = time();
        
        $where = [
            'expire_time' => ['>', 0],
            'expire_time' => ['<', $currentTime],
            'status' => 1
        ];
        
        return $this->updateInfo($where, ['status' => 0, 'update_time' => time()]);
    }
    
    /**
     * 发送消息
     */
    public function sendMessage($data)
    {
        $messageData = [
            'user_id' => $data['user_id'] ?? 0,
            'title' => $data['title'] ?? '',
            'content' => $data['content'] ?? '',
            'type' => $data['type'] ?? self::TYPE_SYSTEM,
            'level' => $data['level'] ?? self::LEVEL_NORMAL,
            'extra_data' => $data['extra_data'] ?? [],
            'relation_type' => $data['relation_type'] ?? '',
            'relation_id' => $data['relation_id'] ?? 0,
            'send_time' => $data['send_time'] ?? time(),
            'expire_time' => $data['expire_time'] ?? 0,
            'status' => 1,
            'create_time' => time(),
            'update_time' => time()
        ];
        
        return $this->insertGetId($messageData);
    }
    
    /**
     * 批量发送消息
     */
    public function sendBatchMessages($userIds, $data)
    {
        $messages = [];
        $currentTime = time();
        
        foreach ($userIds as $userId) {
            $messages[] = [
                'user_id' => $userId,
                'title' => $data['title'] ?? '',
                'content' => $data['content'] ?? '',
                'type' => $data['type'] ?? self::TYPE_SYSTEM,
                'level' => $data['level'] ?? self::LEVEL_NORMAL,
                'extra_data' => is_array($data['extra_data'] ?? []) ? json_encode($data['extra_data'], JSON_UNESCAPED_UNICODE) : '',
                'relation_type' => $data['relation_type'] ?? '',
                'relation_id' => $data['relation_id'] ?? 0,
                'send_time' => $data['send_time'] ?? $currentTime,
                'expire_time' => $data['expire_time'] ?? 0,
                'status' => 1,
                'create_time' => $currentTime,
                'update_time' => $currentTime
            ];
        }
        
        return $this->saveAll($messages);
    }
    
    /**
     * 获取消息统计
     */
    public function getMessageStatistics($startTime = null, $endTime = null)
    {
        $where = ['status' => 1];
        
        if ($startTime) {
            $where['send_time'] = ['>=', $startTime];
        }
        
        if ($endTime) {
            if (isset($where['send_time'])) {
                $where['send_time'] = ['between', [$startTime, $endTime]];
            } else {
                $where['send_time'] = ['<=', $endTime];
            }
        }
        
        // 总消息数
        $totalCount = $this->stat($where, 'count');
        
        // 已读消息数
        $readWhere = array_merge($where, ['is_read' => 1]);
        $readCount = $this->stat($readWhere, 'count');
        
        // 未读消息数
        $unreadWhere = array_merge($where, ['is_read' => 0]);
        $unreadCount = $this->stat($unreadWhere, 'count');
        
        // 按类型统计
        $typeStats = [];
        for ($type = 1; $type <= 5; $type++) {
            $typeWhere = array_merge($where, ['type' => $type]);
            $typeStats[$type] = $this->stat($typeWhere, 'count');
        }
        
        return [
            'total_count' => $totalCount,
            'read_count' => $readCount,
            'unread_count' => $unreadCount,
            'type_stats' => $typeStats,
        ];
    }
}